package com.ruoyi.system.service.impl;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Collectors;

import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.exception.CustomException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.vo.TreeSelectEnv;
import com.ruoyi.common.utils.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.system.mapper.CmsCategoryMapper;
import com.ruoyi.system.domain.CmsCategory;
import com.ruoyi.system.service.ICmsCategoryService;

/**
 * 栏目分类Service业务层处理
 * 
 * @author fanpq
 * @date 2020-12-20
 */
@Service
public class CmsCategoryServiceImpl implements ICmsCategoryService 
{
    @Autowired
    private CmsCategoryMapper cmsCategoryMapper;

    /**
     * 查询栏目分类
     * 
     * @param id 栏目分类ID
     * @return 栏目分类
     */
    @Override
    public CmsCategory selectCmsCategoryById(Long id)
    {
        return cmsCategoryMapper.selectCmsCategoryById(id);
    }

    /**
     * 查询栏目分类列表
     * 
     * @param cmsCategory 栏目分类
     * @return 栏目分类
     */
    @Override
    public List<CmsCategory> selectCmsCategoryList(CmsCategory cmsCategory)
    {
        return cmsCategoryMapper.selectCmsCategoryList(cmsCategory);
    }

    /**
     * 获取栏目分类指定分类下的下拉树列表
     *
     * @param id 指定栏目分类ID
     * @return 栏目分类集合
     */
    @Override
    public List<CmsCategory> selectCmsCategoryByLevel(String id)
    {
        return cmsCategoryMapper.selectCmsCategoryByLevel(id);
    }

    /**
     * 新增栏目分类
     * 
     * @param cmsCategory 栏目分类
     * @return 结果
     */
    @Override
    public int insertCmsCategory(CmsCategory cmsCategory)
    {
        cmsCategory.setCreateTime(DateUtils.getNowDate());
        // 按树形结构组装level字段，字段规则：顶层id(0)+二层id+三层id+。。。，最后一层id等于当前记录id
        Long level1 = 0L;
        // 如果是顶级
        if (StringUtils.isNull(cmsCategory.getCategoryParentId()) || level1.equals(cmsCategory.getCategoryParentId())){
            cmsCategory.setLevel("0");
        }else{
            CmsCategory cmsCategoryParent = this.selectCmsCategoryById(cmsCategory.getCategoryParentId());
            cmsCategory.setLevel(cmsCategoryParent.getLevel() + ":" + cmsCategory.getCategoryParentId().toString());
        }
        return cmsCategoryMapper.insertCmsCategory(cmsCategory);
    }

    /**
     * 修改栏目分类
     * 
     * @param cmsCategory 栏目分类
     * @return 结果
     */
    @Override
    public int updateCmsCategory(CmsCategory cmsCategory)
    {
        cmsCategory.setUpdateTime(DateUtils.getNowDate());
        return cmsCategoryMapper.updateCmsCategory(cmsCategory);
    }

    /**
     * 批量删除栏目分类
     * 
     * @param ids 需要删除的栏目分类ID
     * @return 结果
     */
    @Override
    public int deleteCmsCategoryByIds(Long[] ids)
    {
        List<CmsCategory> cmsCategoryList = cmsCategoryMapper.selectCmsCategoryByIds(ids);
        for (CmsCategory cmsCategory:cmsCategoryList){
            List<CmsCategory> cmsCategories = cmsCategoryMapper.selectCmsCategoryByLevel(cmsCategory.getLevel());
            if (cmsCategories.size() > 1){
                throw new CustomException("拟删除的分类下还有子分类，请先删除子分类");
            }
        }
        return cmsCategoryMapper.deleteCmsCategoryByIds(ids);
    }

    /**
     * 删除栏目分类信息
     * 
     * @param id 栏目分类ID
     * @return 结果
     */
    @Override
    public int deleteCmsCategoryById(Long id)
    {
        CmsCategory cmsCategory = cmsCategoryMapper.selectCmsCategoryById(id);
        if (null != cmsCategory) {
            List<CmsCategory> cmsCategories = cmsCategoryMapper.selectCmsCategoryByLevel(cmsCategory.getLevel());
            if (cmsCategories.size() > 0) {
                throw new CustomException("拟删除的分类下还有子分类，请先删除子分类");
            }
        }
        return cmsCategoryMapper.deleteCmsCategoryById(id);
    }

    /**
     * 构建前端所需要下拉树结构
     *
     * @param cmsCategories 栏目列表
     * @return 下拉树结构列表
     */
    @Override
    public List<TreeSelectEnv> buildCateTreeSelect(List<CmsCategory> cmsCategories)
    {
        List<CmsCategory> cateTrees = buildCateTree(cmsCategories);
        return cateTrees.stream().map(TreeSelectEnv::new).collect(Collectors.toList());
    }
    /**
     * 构建前端所需要树结构
     *
     * @param cmsCategories 栏目列表
     * @return 树结构列表
     */
    @Override
    public List<CmsCategory> buildCateTree(List<CmsCategory> cmsCategories)
    {
        List<CmsCategory> returnList = new ArrayList<CmsCategory>();
        List<Long> tempList = new ArrayList<Long>();
        for (CmsCategory cmsCategory : cmsCategories)
        {
            tempList.add(cmsCategory.getId());
        }
        for (Iterator<CmsCategory> iterator = cmsCategories.iterator(); iterator.hasNext();)
        {
            CmsCategory category = (CmsCategory) iterator.next();
            // 如果是顶级节点, 遍历该父节点的所有子节点
            if (!tempList.contains(category.getCategoryParentId()))
            {
                recursionFn(cmsCategories, category);
                returnList.add(category);
            }
        }
        if (returnList.isEmpty())
        {
            returnList = cmsCategories;
        }
        return returnList;
    }

    /**
     * 递归列表
     *
     * @param list
     * @param t
     */
    private void recursionFn(List<CmsCategory> list, CmsCategory t)
    {
        // 得到子节点列表
        List<CmsCategory> childList = getChildList(list, t);
        t.setChildren(childList);
        for (CmsCategory tChild : childList)
        {
            if (hasChild(list, tChild))
            {
                recursionFn(list, tChild);
            }
        }
    }

    /**
     * 得到子节点列表
     */
    private List<CmsCategory> getChildList(List<CmsCategory> list, CmsCategory t)
    {
        List<CmsCategory> tlist = new ArrayList<CmsCategory>();
        Iterator<CmsCategory> it = list.iterator();
        while (it.hasNext())
        {
            CmsCategory n = (CmsCategory) it.next();
            if (n.getCategoryParentId().longValue() == t.getId().longValue())
            {
                tlist.add(n);
            }
        }
        return tlist;
    }

    /**
     * 判断是否有子节点
     */
    private boolean hasChild(List<CmsCategory> list, CmsCategory t)
    {
        return getChildList(list, t).size() > 0 ? true : false;
    }

    /**
     * 校验栏目分类名称是否唯一
     *
     * @param cmsCategory 栏目分类信息
     * @return 结果
     */
    @Override
    public String checkCateNameUnique(CmsCategory cmsCategory)
    {
        Long cmsCategoryId = StringUtils.isNull(cmsCategory.getId()) ? -1L : cmsCategory.getId();
        CmsCategory info = cmsCategoryMapper.checkCateNameUnique(cmsCategory.getCategoryTitle(),cmsCategory.getCategoryParentId());
        if (StringUtils.isNotNull(info) && info.getId().longValue() != cmsCategoryId.longValue())
        {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }
}
